﻿using JzSport.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace JzSport.Api
{
    /// <summary>
    /// 修改头像
    /// </summary>
    class ChangeAvatarAction : AuthPostAction<Params.ChangeAvatarParams,
        Results.ChangeAvatarResult>
    {
        private static object s_lockDirObj = new object();

        protected override ActionResult<Results.ChangeAvatarResult> OnExecute(ActionContext context, SysParameters sysParameters,
            Params.ChangeAvatarParams opParams)
        {
            // 保存文件到文件目录
            string dir = HttpContext.Current.Server.MapPath("~/Resources/Avatars");
            if (!System.IO.Directory.Exists(dir))
            {
                lock (s_lockDirObj)
                {
                    if (!System.IO.Directory.Exists(dir))
                    {
                        System.IO.Directory.CreateDirectory(dir);
                        JizSport.Common.Logger.DebugToTag(LogTag.TAG, "ChangeAvatarAction create Directory:{0}", dir);
                    }
                }
            }

            string[] segments = opParams.File.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            Guid imageId = Guid.NewGuid();
            opParams.File.SaveAs(string.Format("{0}/{1}.{2}", dir, imageId, segments.Last()));

            ImageResource imageResource = new ImageResource();
            imageResource.Id = imageId;
            imageResource.OwnerId = context.AccountId;
            imageResource.CreatedTime = DateTime.Now;
            imageResource.Usage = UsageCode.Activity;
            imageResource.Url = string.Format("./Resources/Avatars/{0}.{1}", imageId, segments.Last());

            ServiceResult<ImageResource> uploadResult = new ImageResourceService().Save(imageResource);

            ServiceResult<string> serviceResult = new AccountService().ChangeAvatar(context.AccountId, uploadResult.Data.Url);

            Results.ChangeAvatarResult actionResult = new Results.ChangeAvatarResult();
            if (serviceResult.ErrorCode == ErrorCode.NoError)
            {
                actionResult.Url = string.Format("{0}{1}", Configs.BaseWebUrl, imageResource.Url);

                return new ActionResult<Results.ChangeAvatarResult>("1.0.1", true, serviceResult.ErrorCode,
                    ErrorCode.ToString(serviceResult.ErrorCode), actionResult);
            }
            return new ActionResult<Results.ChangeAvatarResult>("1.0.1", false, serviceResult.ErrorCode,
                    ErrorCode.ToString(serviceResult.ErrorCode), actionResult);
        }
    }
}
